/*
 * @Description: 
 * @Version: 2.0
 * @Autor: YouLiangxin
 * @Date: 2022-03-30 10:04:36
 * @LastEditors: VsCode
 * @LastEditTime: 2022-03-30 16:12:21
 */
var net = require('net');
var fs = require("fs");
var push = require("./push.js")

var tcp_server = net.createServer();  // 创建 tcp server

var Sockets = {};
var SocketID = 1;

// 监听 端口
tcp_server.listen(5678, function () {
    console.log('tcp_server listening 5678');
});

// 处理客户端连接
tcp_server.on('connection', function (socket) {
    console.log(socket.address());
    Sockets[SocketID] = socket;
    SocketID++;
    DealConnect(socket)
})

tcp_server.on('error', function () {
    console.log('tcp_server error!');
})

tcp_server.on('close', function () {
    console.log('tcp_server close!');
})

// 处理每个客户端消息
function DealConnect(socket) {
    var flag = false;
    var file_count = 0;
    var file = null;
    var timer = null;

    function time_Out() {
        console.log("响应超时.");
        flag = false;
        file_count = 0;
    }

    socket.on('data', function (data) {

        if (flag == false) {
            try {
                var jsonstr = JSON.parse(data);
                console.log(jsonstr);

                //读取文件
                file = null;
                try {
                    var contentText = fs.readFileSync('config.ini', 'utf-8');
                    var config = JSON.parse(contentText);
                    console.log(config);

                    fs.readFile(config.name, function (err, data) {
                        if (err) {
                            console.log("文件读取错误")
                            return console.error(err);
                        }
                        var file_head = { name: config.name, type: "bin", version: config.version, len: data.length };
                        var str = JSON.stringify(file_head);
                        file = data;
                        socket.write(str);
                    });

                    flag = true;
                    timer = setTimeout(time_Out, 3000);

                } catch (e) { console.log("配置文件读取错误") }
            } catch (e) { }
        }
        else {
            /*超时监测*/
            clearTimeout(timer);
            timer = setTimeout(time_Out, 3000);

            console.log("开始发送文件数据", file_count, file.length);
            file_count++;
            if (file_count == 50) {
                file_count = 0;
                flag = false;
            }
        }

        // //超时直接回调
        // clearTimeout(timer);
        // var timer = setTimeout(function () {
        //     console.log("响应超时.");
        // }, 1000);

        // data = data.toString();
        // console.log('received data %s', data);
    })

    // 客户端正常断开时执行
    socket.on('close', function () {
        console.log('client disconneted!', socket.address());
    })

    // 客户端正异断开时执行
    socket.on("error", function (err) {
        console.log('client error disconneted!');
    });
}
